<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Admin extends Admin_Controller
{
	protected $section = 'photos';
	protected $_ci;
	private	$path = '';
	var $wtm_text = "HIGHESCORTS.COM";
	protected $_currentUserGroup;
	protected $_currentUserName = '';
	protected $_curentUserZones;
	public function __construct()
	{
		parent::__construct();
		
		$this->_ci = &get_instance();
		$this->wtm_text = read_file("./config/wtm_text.txt");
		// Load all the required classes
		$this->load->library('form_validation');
		$this->load->library('image_lib');
		$this->lang->load('be_photo');
		$this->config->load('be_photo');
		$this->_path = FCPATH . $this->config->item('upload_image_path');
		$this->_currentUserGroup = $this->_ci->ion_auth->get_user()->group;
		$this->_currentUserName = $this->_ci->ion_auth->get_user()->username;
		$this->_curentUserZones = $this->_ci->escort_user_roles_n_zones_entity->getUserRolesNZones($this->_currentUserName);

		$this->data->filterList = array(
				''		=> lang('escort_be_photo_filter_all_label'),
				'1'		=> lang('escort_be_photo_filter_reviewed_label'),
				'0'		=> lang('escort_be_photo_filter_unreviewed_label')
			);
		
		$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
						->append_metadata(js('jquery.form.js', 'be_photo'))
						->append_metadata(js('escort.be.photo.js', 'be_photo'))
						->append_metadata(js('jquery.simplemodal.js', 'be_photo'))
						->append_metadata(js('jquery.Jcrop.min.js', 'be_photo'))
						->append_metadata(css('jquery.Jcrop.css', 'be_photo'))
						->append_metadata(css('confirm.css', 'be_photo'))
						->append_metadata(css('osx.css', 'be_photo'))
						->append_metadata(css('escort.be.photo.css', 'be_photo'));
	}

	/**
	 * List all items
	 */
	public function index($status = '')
	{
		//set the base/default where clause
		$base_where = array();
	
		if($status != ''){
			$review = $status;
		}else{
			$review = $this->input->post('f_review');
		}
		if($review == null){
			$review = 0;
		}
		$escortName = $this->input->post('f_escort_name');
		if($escortName == null){
			$escortName = '';
		}
		$escortIdList = $this->_ci->user_entity->getEscortIdListByAdmin($this->_currentUserName, $this->_currentUserGroup , $this->_curentUserZones, $escortName);
		if($escortIdList && count($escortIdList) > 0){
			// Create pagination links
			$total_rows = $this->_ci->media_entity->countMediaListByEscortIdList($escortIdList, $review);
			$pagination = create_pagination('admin/be_photo/index', $total_rows);
			
			// Using this data, get the relevant results
			$photos = $this->_ci->media_entity->getMediaListByEscortIdList($escortIdList,$pagination['limit'], $review);
		}else{
			$pagination = null;
			$photos = null;
		}
		//do we need to unset the layout because the request is ajax?
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
		$this->template
			->title($this->module_details['name'])
			->append_metadata(js('jwplayer.js', 'be_photo'))
			->append_metadata(js('escort.be.photo.filter.js', 'be_photo'))
			->set('pagination', $pagination)
			->set('photos', $photos);

		$this->input->is_ajax_request() ? $this->template->build('admin/tables/posts', $this->data) : $this->template->build('admin/index', $this->data);
			
	}
	
	public function edit($id = 0)
	{
		$this->data->permissionList = array(
			'public'		=> 'Public',
			'public_top'	=> 'Public Top',
			'private'		=>	'Private'
		);
		$id OR die();
		$media = $this->_ci->media_entity->init('id',$id);
		if($this->input->post('add')){
			$result = array();
			$error = false;
			if(isset($_FILES['image_file'])){
				$escort = $this->_ci->escort_entity->init('id',$media->getEscortId());
				$result['file'] = true;
				$config['upload_path'] = $this->_path.$escort->getUserId();
				$config['allowed_types'] = $this->config->item('files_allowed_file_ext');
				$config['max_size']	= $this->config->item('max_size');
				$config['max_width']  = $this->config->item('max_width');
				$config['max_height']  = $this->config->item('max_height');
		
				$this->load->library('upload', $config);
		
				if ( ! $this->upload->do_upload('image_file')){
					$error = array('error' => $this->upload->display_errors());
					$result['result'] = false;
					$result['upload_path'] = $config['upload_path'];
					$result['message'] = $this->upload->display_errors();
					$error = true;
				}else{
					$data = $this->upload->data();
					$originalFile = $this->renameMediaFileUpload($media, $data['file_name']);
					$media->setName($originalFile);
					$media->setPublicTopImageBig($this->processTopBigPicture($media, $originalFile));
					$media->setPublicTopImageThin($this->processTopThinPicture($media, $originalFile));
					$media->setPublicImage($this->processPublicPicture($media, $originalFile));
				}
			}
			if(!$error){		
				$media->setPermission($this->input->post('permission'));
				$media->setReview($this->input->post('image_reviewed'));
				$media->setAltText($this->input->post('alt_text'));
				$media->setDescText($this->input->post('desc_text'));
				
				if(!$media->getAddPoint() && $media->getReview()){
					$media->setAddPoint(1);
					$escort = $this->_ci->escort_entity->init('id', $media->getEscortId());
					$escort->setPoint($escort->getPoint() + 10);
					$escort->update();
					$POINT_LOG = $this->CI->point_log_entity->createNewEntity();
				    $POINT_LOG->setAction('ADD');
				    $POINT_LOG->setEscortId($escort->getId());
				    $POINT_LOG->setAmount(10);
				    $POINT_LOG->setCurrentPoint($escort->getPoint());
				    $POINT_LOG->setSiteRef(SITE_REF);
				    $POINT_LOG->setDescription('ADD POINT WHEN SET REVIEWED PHOTO');
				    $POINT_LOG->update();
				} 
				$media->update();
				
				do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_update_photo', array($id));
				$result['result'] = true;
				$result['message'] = lang('escort_be_photo_update_success');
				$this->session->set_flashdata('success', $this->lang->line('escort_be_photo_update_success'));
			}
			echo json_encode($result);
		}else{
			//$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
			$this->template->set_layout(FALSE);
			$this->template
			->set('media', $media)
			->build('admin/form', $this->data);
		}
	}
	public function delete()
	{	
		$id = $this->input->post('id');
		$result = array();
		if($this->_ci->media_entity->delete($id)){
			$result['result'] = true;
			$result['message'] = lang('escort_be_photo_delete_success');
			do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_delete_photo', array($id));
		}else{
			$result['result'] = false;
			$result['message'] = lang('escort_be_photo_delete_error');
		}
		echo json_encode($result);
	}
	
	private function renameMediaFileUpload( $MEDIA, $oldFile){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		
		$sExtension = strtolower ( substr( $oldFile, ( strrpos($oldFile, '.') + 1 ) ) );
		$newFile = "file_media_".$MEDIA->getId().".$sExtension";
		rename ( "./uploads/default/users/".$ESCORT->getUserId()."/".$oldFile, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
		return $newFile;			
	}
	
	private function processTopBigPicture($MEDIA, $originalFileName){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		$sExtension = strtolower ( substr( $originalFileName, ( strrpos($originalFileName, '.') + 1 ) ) );
		$newFile = "file_media_top_big_".$this->digit->rand_digit(5)."_".$MEDIA->getId().".$sExtension";
		copy ( "./uploads/default/users/".$ESCORT->getUserId()."/".$originalFileName, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
	
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		$config['x_axis'] = '0';
		$config['y_axis'] = '0';
		$config['maintain_ratio'] = FALSE;
		
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (PUBLIC_TOP_W >= $size[0]) ? $size[0]:PUBLIC_TOP_W;
		$config['height'] = (PUBLIC_TOP_H >= $size[1]) ?$size[1]:PUBLIC_TOP_H;
		
		$this->image_lib->initialize($config);
		$this->image_lib->crop();
		$this->image_lib->clear();
		
		$this->wtm_center("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= ($config['height'] - 76)/2 );
		$this->wtm_bottom_left("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= ($config['height'] - 76) );
				
		return $newFile;				
	}
	
	private function processTopThinPicture($MEDIA, $originalFileName){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		$sExtension = strtolower ( substr( $originalFileName, ( strrpos($originalFileName, '.') + 1 ) ) );
		$newFile = "file_media_top_thin_".$this->digit->rand_digit(5)."_".$MEDIA->getId().".$sExtension";
		copy ( "./uploads/default/users/".$ESCORT->getUserId()."/".$originalFileName, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
		
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		$config['x_axis'] = '0';
		$config['y_axis'] = '0';
		$config['maintain_ratio'] = FALSE;
		
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (TOP_THIN_W >= $size[0]) ? $size[0]:TOP_THIN_W;
		$config['height'] = (TOP_THIN_H >= $size[1]) ?$size[1]:TOP_THIN_H;
		 
		
		$this->image_lib->initialize($config);
		$this->image_lib->crop();
		$this->image_lib->clear();
		$this->wtm_center("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= $config['height']-105);
				
		return $newFile;				
	}
	
	private function processPublicPicture($MEDIA, $originalFileName){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		$sExtension = strtolower ( substr( $originalFileName, ( strrpos($originalFileName, '.') + 1 ) ) );
		$newFile = "file_media_public_".$this->digit->rand_digit(5)."_".$MEDIA->getId().".$sExtension";
		copy ( "./uploads/default/users/".$ESCORT->getUserId()."/".$originalFileName, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
		
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		$config['x_axis'] = '0';
		$config['y_axis'] = '0';
		$config['maintain_ratio'] = FALSE;
		
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (PUBLIC_W >= $size[0]) ? $size[0]:PUBLIC_W;
		$config['height'] = (PUBLIC_H >= $size[1]) ?$size[1]:PUBLIC_H;
		
		$this->image_lib->initialize($config);
		$this->image_lib->crop();
		$this->image_lib->clear();
		
		$this->wtm_center("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= ($config['height']-84)/2);
		$this->wtm_bottom_left("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= $config['height']-84);
				
		return $newFile;				
	}
	
	private function wtm_center($file, $text, $margin_top= 250){
		$config['source_image'] = $file;
		$config['wm_text'] = $text;
		$config['wm_type'] = 'text';
		$config['wm_font_path'] = './captcha/fonts/arial.ttf';
		$config['wm_font_size'] = '14';
		$config['wm_font_color'] = '#aaaaaa';
		$config['wm_vrt_alignment'] = 'center';
		$config['wm_hor_alignment'] = 'center';
		$config['wm_hor_offset'] = '0';
		$config['wm_vrt_offset'] = "$margin_top";
		$this->image_lib->initialize($config);
		$this->image_lib->watermark();	
		$this->image_lib->clear();
	}
	
	private function wtm_bottom_left($file, $text, $margin_top= 500){
		$config['source_image'] = $file;
		$config['wm_overlay_path'] = './config/wtm_image.png';
		$config['wm_type'] = 'overlay';
		$congif['wm_opacity'] = 80;
		//$config['wm_font_path'] = './captcha/fonts/arial.ttf';
		//$config['wm_font_size'] = '14';
		//$config['wm_font_color'] = '#aaaaaa';
		$config['wm_vrt_alignment'] = 'top';
		$config['wm_hor_alignment'] = 'left';
		$config['wm_hor_offset'] = '50';
		$config['wm_vrt_offset'] = "$margin_top";
		$this->image_lib->initialize($config);
		$this->image_lib->watermark();	
		$this->image_lib->clear();
	}
	public function download($id = 0){
		$this->load->helper('download');
		$media = $this->_ci->media_entity->init('id',$id);
		$data = file_get_contents($media->getTargetFile());
		force_download($media->getName() , $data);
	}
	public function change_review($id){
		$media = $this->_ci->media_entity->init('id',$id);
		$result = array();
		$result['result'] = false;
		if($media){
			if($media->getReview()){
				$media->setReview(0);
				$result['text'] = lang('escort_be_photo_unreviewed_label');
				do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_mark_media_as_unreviewed', array($id));
			}else{
				$media->setReview(1);
				$result['text'] = lang('escort_be_photo_reviewed_label');
				do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_mark_media_as_reviewed', array($id));
			}
			if(!$media->getAddPoint() && $media->getReview()){
				$media->setAddPoint(1);
				$escort = $this->_ci->escort_entity->init('id', $media->getEscortId());
				$escort->setPoint($escort->getPoint() + 10);
				$escort->update();
			}
			
			$media->update();
			$result['result'] = true;
			
		}
		echo json_encode($result);
	}
	public function play_video($id){
		$media = $this->_ci->media_entity->init('id',$id);
		$media or die();
		$this->template->set_layout(FALSE);
		$this->template
		->set('media', $media)
		->build('admin/play_video', $this->data);
	}
}
